package com.health.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.health.common.enums.OrderStatus;
import com.health.common.enums.PayType;
import com.health.system.domain.MallOrderCloseRequest;
import com.health.system.domain.OrderAddressUpdateRequest;
import com.health.system.domain.UserAddress;
import com.health.system.domain.vo.OrderDetailVO;
import com.health.system.service.IUserAddressService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.system.domain.MallOrder;
import com.health.system.service.IMallOrderService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author ruoyi
 * @date 2025-10-29
 */
@RestController
@RequestMapping("/system/order")
public class MallOrderController extends BaseController
{
    @Autowired
    private IMallOrderService mallOrderService;
    @Autowired
    private IUserAddressService userAddressService;

    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallOrder mallOrder)
    {
        startPage();
        List<MallOrder> list = mallOrderService.selectMallOrderList(mallOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MallOrder mallOrder)
    {
        List<MallOrder> list = mallOrderService.selectMallOrderList(mallOrder);
        ExcelUtil<MallOrder> util = new ExcelUtil<MallOrder>(MallOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        return success(mallOrderService.selectMallOrderByOrderId(orderId));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallOrder mallOrder)
    {
        return toAjax(mallOrderService.insertMallOrder(mallOrder));
    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallOrder mallOrder)
    {
        return toAjax(mallOrderService.updateMallOrder(mallOrder));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(mallOrderService.deleteMallOrderByOrderIds(orderIds));
    }
    /**
     * 订单状态变更
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{orderId}/{status}")
    public AjaxResult changeStatus(@PathVariable("orderId") Long orderId, @PathVariable("status") String status)
    {
        if (OrderStatus.getByCode( status)==null){
            return error("无效订单状态");
        }
        MallOrder mallOrder = mallOrderService.selectMallOrderByOrderId(orderId);
        if (mallOrder == null){
            return error("订单不存在");
        }

        //验证订单状态流转不合法
        if (!isValidStatusTransition(mallOrder.getStatus(), status)){
            return error("订单状态流转不合法");
        }
        //设置订单状态
        mallOrder.setStatus(status);
        //设置订单状态时间
        setStatusTime(mallOrder, status);

        return toAjax(mallOrderService.updateMallOrder(mallOrder));
    }
    /**
     * 验证状态流转是否合法
     */
    private boolean isValidStatusTransition(String currentStatus, String targetStatus) {
        // 这里可以定义状态流转规则
        // 例如：只能从待付款->待发货->待收货->已完成
        // 或者允许取消订单等

        // 简单的验证：不允许回退状态
        int current = Integer.parseInt(currentStatus);
        int target = Integer.parseInt(targetStatus);

        // 允许向前推进状态，或者取消订单（状态4）
        return target > current || "4".equals(targetStatus);
    }

    /**
     * 根据状态设置相应的时间
     */
    private void setStatusTime(MallOrder order, String status) {
        Date now = new Date();
        switch (status) {
            case "1": // 待发货（已支付）
                order.setPayTime(now);
                break;
            case "2": // 待收货（已发货）
                order.setDeliveryTime(now);
                break;
            case "3": // 已完成（已收货）
                order.setReceiveTime(now);
                break;
            case "4": // 已取消
                // 可以设置取消时间等
                break;
        }
    }
    /**
     * 获取订单状态数量统计
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/statusCount")
    public AjaxResult getOrderStatusCount(MallOrder mallOrder) {
        Map<String, Integer> countMap = mallOrderService.getOrderCountByStatus(mallOrder);
        return success(countMap);
    }
    /**
     * 获取订单状态枚举
     */
    @GetMapping("/statusEnums")
    public AjaxResult getStatusEnums() {
        Map<String, String> enums = new HashMap<>();
        for (OrderStatus status : OrderStatus.values()){
            enums.put(status.getCode(), status.getDesc());
        }
        return success(enums);
    }
    /**
     * 获取支付方式枚举
     */
    @GetMapping("/payTypeEnums")
    public AjaxResult getPayTypeEnums() {
        Map<String, String> enums = new HashMap<>();
        for (PayType payType : PayType.values()){
            enums.put(payType.getCode(), payType.getDesc());
        }
        return success(enums);
    }

    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/close")
    public AjaxResult closeOrder(@RequestBody MallOrderCloseRequest closeRequest){
        //验证订单是否存在
        MallOrder mallOrder = mallOrderService.selectMallOrderByOrderId(closeRequest.getOrderId());
        if (mallOrder == null){
            return error("订单不存在");
        }
        //验证订单状态是否可关闭，已完成不可关闭
        if ("3".equals(mallOrder.getStatus()) || "4".equals(mallOrder.getStatus())){
            return error("已完成或已取消的订单不能关闭");
        }
        return toAjax(mallOrderService.closeOrder(closeRequest));
    }

    /**
     * 修改订单收货地址
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "修改订单收货地址", businessType = BusinessType.UPDATE)
    @PutMapping("/address")
    public AjaxResult updateOrderAddress(@RequestBody OrderAddressUpdateRequest updateRequest){
        MallOrder mallOrder = mallOrderService.selectMallOrderByOrderId(updateRequest.getOrderId());
        if (mallOrder == null){
            return error("订单不存在");
        }
        MallOrder updateOrder = new MallOrder();
        updateOrder.setOrderId(updateRequest.getOrderId());
        updateOrder.setAddressId(updateRequest.getNewAddressId());

        return toAjax(mallOrderService.updateMallOrder(updateOrder));
    }
    /**
     * 获取用户地址列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/address/user/{userId}")
    public AjaxResult getUserAddressList(@PathVariable("userId") Long userId) {
        List<UserAddress> addressList = userAddressService.selectUserAddressByUserId(userId);
        return success(addressList);
    }
    /**
     * 根据地址ID获取地址详情
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/detail/{addressId}")
    public AjaxResult getAddressDetail(@PathVariable Long addressId) {
        UserAddress address = userAddressService.selectUserAddressByAddressId(addressId);
        if (address == null) {
            return error("地址不存在");
        }
        return success(address);
    }
}
